//
//  PYCAppDelegate.m
//  PinyinContacts
//
//  Created by Xiaoping Zhang on 2/15/10.
//  Copyright 2010 Filters, Inc. All rights reserved.
//

#import "PYCAppDelegate.h"
#import "PYCGroupTableController.h"
#import "PYCContactTableController.h"

#import <AddressBook/ABGroup.h>

@interface PYCAppDelegate ()

- (void)groupTableViewSelectionDidChange:(NSNotification *)note;

@end

@implementation PYCAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification 
{
	// Insert code here to initialize your application 
}

-(void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(groupTableViewSelectionDidChange:)
												 name:NSTableViewSelectionDidChangeNotification
											   object:groupTableView];
}

-(void) dealloc
{
	[super dealloc];
	
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)groupTableViewSelectionDidChange:(NSNotification *)note
{
	NSInteger selectedRow = [groupTableView selectedRow];
	if (selectedRow < 0 || selectedRow == NSNotFound)
	{
		return;
	}
	
	id groupTableDataSource = [groupTableView dataSource];
	if (!groupTableDataSource || ![groupTableDataSource isKindOfClass:[PYCGroupTableController class]])
	{
		return;
	}
	
	PYCGroupTableController *groupTableController = (PYCGroupTableController *)groupTableDataSource;
	if (selectedRow >= [groupTableController countOfGroups])
		return;
	
	ABGroup *selectedGroup = [groupTableController groupAtIndex:selectedRow];
	if (!selectedGroup)
		return;
	
	id contactTableDataSource = [contactTableView dataSource];
	if (!contactTableDataSource || ![contactTableDataSource isKindOfClass:[PYCContactTableController class]])
		return;
	
	PYCContactTableController *contactTableController = (PYCContactTableController *)contactTableDataSource;
	[contactTableController setContacts:[selectedGroup members]];
	
	[contactTableView reloadData];
}

@end
